<?php namespace app\http\controllers\site;

use App\Http\Controllers\Controller;
use GuzzleHttp\Psr7\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Contest;

class ContestController extends Controller
{
    //申请
    public function getApply()
    {
        return view('contest.apply',[

        ]);
    }


    public function getIndex()
    {
        return view('contest.index',[
        ]);
    }

    public function getList(Request $request)
    {
        $lists = Contest::orderBy('created_at', 'desc')->paginate(10);
        if($request->has('page') && $request['page']>0){
            return \Response::json($lists);
        }else{
            return view('contest.list',[
                'lists' => $lists
            ]);
        }
    }

    public  function postApply(Request $request){
        $contest = Contest::create([
            'advertisement' => $request['advertisement'],
            'nickname' => $request['nickname'],
            'author' => $request['author'],
            'phone' => $request['phone'],
            'explain' => $request['explain'],
        ]);

        if($contest && $contest->id){
            $ret = ['state' => 'success', 'message' => '操作成功'];
        }else{
            $ret = ['state' => 'fail', 'message' => '操作失败'];
        }
        return \Response::json($ret);
    }

    public function postVote(Request $request){
        $count = DB::table("contests_vote")
            ->where("contestId",$request['id'])
            ->where("ip", $request['ip'].'_'.$this->get_inter())
            ->whereBetween('created_at',[date('Y-m-d 00:00:00',time()) , date('Y-m-d 23:59:59',time())])
            ->count();
        if($count>0){
            $ret = ['state' => 'fail', 'message' => '今天您已经给这个推广语投过一票！'];
        }else{
            DB::transaction(function () use($request){
                DB::table("contests")->where("id", $request["id"])->increment("vote");
                DB::table("contests_vote")->insert(["contestId"=>$request["id"], "ip"=>$request['ip'].'_'.$this->get_inter()]);
            });
            $ret = ['state' => 'success', 'message' => '投票成功'];
        }
        return \Response::json($ret);
    }

    private function get_inter()
    {
        $onlineip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;
    }
}